package com.hp.dao;

import com.hp.entity.User;
import com.hp.entity.dto.UserDto;
import com.hp.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class UserDao {
    public UserDto getUser(String account) throws RuntimeException{
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        String sql="select u.id as id," +
                "u.department_id as departmentId," +
                "u.user_type as userType," +
                "u.head_url as headUrl," +
                "u.account as account," +
                "u.user_name as userName," +
                "u.password as password," +
                "u.salt as salt," +
                "u.created_time as createdTime," +
                "u.updated_time as updatedTime," +
                "u.created_user_id as createdUserId," +
                "r.role_name as roleName " +
                "from sys_users u " +
                "left join sys_roles r on r.id=u.user_type " +
                "where account=?";
        try {
            return queryRunner.query(sql,new BeanHandler<UserDto>(UserDto.class),account);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<UserDto> getUserListByPage(Map<String, Object> map) {
        String sql="select u.id as id," +
                "u.department_id as departmentId," +
                "u.user_type as userType," +
                "u.head_url as headUrl," +
                "u.account as account," +
                "u.user_name as userName," +
                "u.password as password," +
                "u.salt as salt," +
                "u.created_time as createdTime," +
                "u.updated_time as updatedTime," +
                "u.created_user_id as createdUserId," +
                "r.role_name as roleName " +
                "from sys_users u " +
                "left join sys_roles r on r.id=u.user_type " +
                "where 1=1 order by u.id desc limit ?,?";
        StringBuilder sb=new StringBuilder(sql);
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        int currentPage = Integer.parseInt(map.get("currentPage").toString())-1;
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        try {
            return queryRunner.query(sb.toString(),new BeanListHandler<UserDto>(UserDto.class),
                    currentPage*pageSize,pageSize);
        }  catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Long totalUser(Map<String, Object> map) {
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        StringBuilder sb=new StringBuilder();
        sb.append("select count(*) as rows from sys_users");
        String sql=sb.toString();
        try {
            return (Long)queryRunner.query(sql, new ScalarHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean addUser(User user) {
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        String sql="insert into sys_users(id,department_id,user_type,account,user_name,password,salt," +
                "created_time,updated_time,created_user_id) values(null,?,?,?,?,?,?,?,?,?)";
        try {
           return queryRunner.update(sql,
                   user.getDepartmentId(),
                   user.getUserType(),
                   user.getAccount(),
                   user.getUserName(),
                   user.getPassword(),
                   user.getSalt(),
                   user.getCreatedTime(),
                   user.getUpdatedTime(),
                   user.getCreatedUserId())>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<User> getDocterList(String sign, String departmentId) {
        String sql="SELECT id,user_name AS userName FROM sys_users " +
                "WHERE  id IN( SELECT user_id FROM SCHEDULE WHERE department_id=? AND SIGN=?)";
        StringBuilder sb=new StringBuilder(sql);
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        try {
            return queryRunner.query(sb.toString(),new BeanListHandler<User>(User.class),
                  departmentId,sign);
        }  catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能1：重载getDocterList方法，用于分页查询的条件。
     * @param departmentId
     * @return
     */
    public List<User> getDocterList(String departmentId) {
        String sql="SELECT id,user_name AS userName FROM sys_users " +
                "WHERE  id IN( SELECT user_id FROM SCHEDULE WHERE department_id=?)";
        StringBuilder sb=new StringBuilder(sql);
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        try {
            return queryRunner.query(sb.toString(),new BeanListHandler<User>(User.class),
                    departmentId);
        }  catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public User getUserById(Integer userId) {
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        String sql="select u.id as id," +
                "u.department_id as departmentId," +
                "u.user_type as userType," +
                "u.head_url as headUrl," +
                "u.account as account," +
                "u.user_name as userName," +
                "u.password as password," +
                "u.salt as salt," +
                "u.created_time as createdTime," +
                "u.updated_time as updatedTime," +
                "u.created_user_id as createdUserId " +
                "from sys_users u " +
                "where u.id=?";
        try {
            return queryRunner.query(sql,new BeanHandler<UserDto>(UserDto.class),userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean editUserInfo(User user) {
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        String sql="update  sys_users set password=?,head_url=?,salt=? where id=?";
        try {
            return queryRunner.update(sql,
                    user.getPassword(),
                    user.getHeadUrl(),
                    user.getSalt(),
                    user.getId())>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean updateUserHeadUrl(String headUrl, String id) {
        QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
        String sql="update  sys_users set head_url=? where id=?";
        try {
            return queryRunner.update(sql, headUrl,id)>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
